<?php
class Shop_Model_Detail extends Shop_Model_Base{

	/**
	 * 表示用変換
	 *
	 * @param $shopDtl
	 * @param $apalogurl
	 * @param $tenpoimageurl
	 */
	public function convertData($shopDtl, $apalogurl="", $tenpoimageurl="")
	{
		$detail = $shopDtl;

		// 免許番号
		$license = $shopDtl['M05_MENKYO_HAKKOUMOTO'];
		if ($shopDtl['M05_MENKYO_KOUSHINKAI'] != '') $license .= '(' . $shopDtl['M05_MENKYO_KOUSHINKAI'] . ')';
		$license .= $shopDtl['M05_MENKYO_GOUSUU'];
		$detail['LICENSE'] = $license;

		// URL
		$url = '';
		if ($shopDtl['M05_TENPO_URL'] != '')
		{
			$url = $shopDtl['M05_TENPO_URL'];
			// URLに｢http://｣「https://」が含まれていない場合
			if (strpos($url, 'http://') === false && strpos($url, 'https://') === false) $url = 'http://' . $url;
		}
		$detail['URL'] = $url;

		// 郵便番号
		$detail['M05_TENPO_YUUBIN'] = substr($shopDtl['M05_TENPO_YUUBIN'], 0, 3) . '-' . substr($shopDtl['M05_TENPO_YUUBIN'], 3, 4);

	    //【START】
		//2011-06-21_#0363_【バグ】店舗住所にて機種依存文字が文字化けする
		//内容：店舗名、住所、番地、備考をユニコードに変換
		//担当：SS榊原

		$detail['M05_JYUUSHO_TEXT'] = Apm_Util::replaceUnicode($detail['M05_JYUUSHO_TEXT']);
		$detail['M05_TENPO_BANCHI'] = Apm_Util::replaceUnicode($detail['M05_TENPO_BANCHI']);
		$detail['M05_TENPO_JYUUSHO_BIKOU'] = Apm_Util::replaceUnicode($detail['M05_TENPO_JYUUSHO_BIKOU']);

		//【END】
		//2011-06-21_#0363_【バグ】店舗住所にて機種依存文字が文字化けする
		//内容：店舗名、住所、番地、備考をユニコードに変換

		// 定休日
    	$detail['M05_TEIKYUUBI_NAME'] = $this->convertTeikyuubi($shopDtl);

    	//【START】
		//2011-06-21_#0363_【バグ】店舗住所にて機種依存文字が文字化けする
		//内容：店舗名、営業時間をユニコードに変換
		//担当：SS榊原

		$detail['M05_TENPO_NAME'] = Apm_Util::replaceUnicode($detail['M05_TENPO_NAME']);
		// 営業時間変換
		$detail['EIGYOU_ZIKAN'] = Apm_Util::replaceUnicode($this->convertEigyouZikan($shopDtl));

		//【END】
		//2011-06-21_#0363_【バグ】店舗住所にて機種依存文字が文字化けする
		//内容：店舗名、営業日をユニコードに変換

		// 地域情報ｻｲﾄ Url取得処理
		$prefCd = $shopDtl['M05_TENPO_TODOUFUKEN_CD'];
		$detail['APALOG_URL'] = Apm_Config_Shop::$PREF_URL_LIST["$prefCd"];

		// 無料電話番号
		$callData = $this->convertFreeCalling($shopDtl);
		$detail['IS_FREE_CALL']  = $callData['IS_FREE_CALL'];
		$detail['TEL_01']        = $callData['TEL_01'];
		$detail['TEL_02']        = $callData['TEL_02'];
		$detail['hasFreeTel']    = $callData['hasFreeTel'];
		$detail['CONNECTION_NO'] = $callData['CONNECTION_NO'];
		$detail['M05_TENPO_LINE_ID'] = Apm_ShopUtil::getTenpoLineId($shopDtl['M05_TENPO_CD']);
		$detail['LINE_URL'] = Apm_Config_Shop::URL_LINE;
		
		//高津情報変換
		$detail['KOUTSUU_STR'] = Apm_ShopUtil::GetTrafficStr($detail);
		
		// スタッフ写真
		$detail['STAFF_IMAGE_PATH'] = $tenpoimageurl . 's' . Apm_ShopUtil::getOldTenpoCd($shopDtl['M05_TENPO_CD']) . '.jpg';
		// 店舗外観写真
		$detail['SHOP_IMAGE_PATH'] = $tenpoimageurl . 'g' . Apm_ShopUtil::getOldTenpoCd($shopDtl['M05_TENPO_CD']) . '.jpg';


/* DBからアパログデータを取得する 2011.10.26 M.Nagata Start */
		//アパログURLが有効な場合のみコンテンツ取得処理実行
		if($apalogurl!="")
		{
			// アパログ
			$detail['apalogFlg'] = false;
			
			$this->_model_blog = new Shop_Model_TweetAndBlog();
			// アパログ情報取得
			$detail['apalogInfo'] = $this->_model_blog->getApalogForShopDetail($shopDtl['M05_TENPO_CD']);
			
			// アパログ情報が存在する場合、フラグを立てる
			if( count($detail['apalogInfo']) > 0)
			{
				$detail['apalogFlg'] = true;
			}
		}
/* DBからアパログデータを取得する 2011.10.26 M.Nagata End */

		// 加盟店ページURL
		$detail['SHOP_PAGE_URL'] = Apm_Bukkenurl::generateUrlByParametersShopDetail(array_merge($shopDtl, array('Category'=>'9')));

		return $detail;
	}

	/**
	 * ショップNoから店舗コードを取得
	 *
	 * @param ショップNo
	 * @return 店舗コード（取得できなかった場合はnull）
	 */
	public function getShopCd($shopNo)
	{

$sql = <<< DOC_END

		SELECT
		    M74_TENPO_CD TENPO_CD
		FROM
		    M74TENPO_SEARCHNO
		WHERE
		    M74_TENPO_SEARCH_NO = '{$shopNo}'
DOC_END;

		$shopDtl = $this->dbGetData($sql);

        // 店舗が存在しない場合
        if (is_array($shopDtl) == false) return null;

		return $shopDtl['TENPO_CD'];
	}

	/**
	 * twitter情報取得
	 *
	 * @param $shopCd
	 * @return twitter情報（取得できなかった場合はnull）
	 */
	public function getTwitterInfo($shopCd)
	{
		$db_params = array();
		$db_params['shopCd'] = $shopCd;

$sql = <<< DOC_END

SELECT
        M96_TENPO_CD
        ,M96_TENPO_NAME
        ,M96_TWITTER_ACCOUNT
        ,M96_TWITTER_PASSWORD
    FROM
        M96MINIBLOG
    WHERE
        M96_TENPO_CD = :shopCd

DOC_END;

		$twitter = $this->dbGetData($sql, $db_params);

        // 店舗が存在しない場合
        if (is_array($twitter) == false) return null;

        return $twitter;
	}

    /**
     * 店舗詳細取得sql文生成
     * sql文生成
     * @param $params
     * @param $db_params
     * @return sql文
     */
	protected function generateSql($params, &$db_params)
    {
    	$strShopCd = $params['ShopCd'];

$sql = <<< DOC_END
		SELECT
	        A.M05_TENPO_CD
	        ,M05_TENPO_NAME
	        ,M05_TENPO_URL
	        ,M05_TENPO_YUUBIN
	        ,M05_TENPO_TODOUFUKEN_CD
	        ,M05_TENPO_TODOUFUKEN
	        ,M05_TENPO_SHIKUCHOUSON
	        ,M05_TENPO_SHIKUCHOUSON_CD
	        ,M05_TENPO_TEL01
	        ,M05_TENPO_TEL02
	        ,M05_TENPO_MAIL
	        ,M05_JYUUSHO_TEXT
	        ,M05_TENPO_BANCHI
	        ,M05_TENPO_JYUUSHO_BIKOU
	        ,M05_TENPO_FAX
	        ,M05_EIGYOU_ZIKAN_OPEN_M
	        ,M05_EIGYOU_ZIKAN_CLOSE_H
	        ,M05_EIGYOU_ZIKAN_CLOSE_M
	        ,M05_EIGYOU_ZIKAN_OPEN_H
	        ,M05_EIGYOU_ZIKAN_BIKOU
	        ,M05_TEIKYUUBI
	        ,M05_TEIKYUUBI_BIKOU
	        ,M05_HOUZINMEI
	        ,M05_TENPO_ANNAI_FLAG
	        ,M05_MENKYO_HAKKOUMOTO
	        ,M05_MENKYO_KOUSHINKAI
	        ,M05_MENKYO_GOUSUU
	        ,M05_KOUTSUU_TEXT01
	        ,M05_KOUTSUU_BIKOU01
	        ,M05_TOHO01
	        ,M05_TENPO_IDO
	        ,M05_TENPO_KEIDO
	        ,M05_OEM
	        ,M05_HOUZIN_CD
	        ,M05_TOKUCHO01
	        ,M05_TOKUCHO02
	        ,M05_TOKUCHO03
	        ,M05_TOKUCHO04
	        ,M05_TOKUCHO05
	        ,M05_TOKUCHO06
	        ,M05_TOKUCHO07
	        ,M05_TOKUCHO08
	        ,M05_TOKUCHO09
	        ,M05_TOKUCHO10
	        ,M05_TOKUCHO11
	        ,M05_TOKUCHO12
	        ,M05_TOKUCHO13
	        ,M05_TOKUCHO14
	        ,M05_TOKUCHO15
	        ,M05_TOKUCHO16
	        ,M03_ROSENZU_EKI_CD
	        ,D.M02_ENSEN_KUBUN
	        ,C.M03_ENSEN_NAME
	        ,C.M03_EKI_NAME
	        ,CASE
	            WHEN LPAD(NVL(M05_EIGYOU_ZIKAN_CLOSE_H, ''), 2, '0') || LPAD(NVL(M05_EIGYOU_ZIKAN_CLOSE_M, ''), 2, '0') > '1900' THEN 1
	            ELSE 0
	        END AS M05_EIGYOU_ZIKAN_CLOSE
			,M05_NEWS01
			,M05_NEWS02
			,M05_NEWS03
			,M05_NEWS_URI01
			,M05_NEWS_URI02
			,M05_NEWS_URI03
DOC_END;
for ($call_no=1; $call_no<=Apm_Config_Shop::CALLNOTE_NO_MAX; $call_no++) {
	$sql .= " ,M93_CONNECTION_NO".$call_no;
	$sql .= " ,M93_CONTROL_FLAG".$call_no;
}
$sql .= <<< DOC_END
	        ,M93_USE_KBN
	        ,M93_START_DATE
	        ,M93_DEL_DATE
	        ,
	        NVL(SUBSTR(M05_SERVICE_FLAG, 14, 1), '0') SELF_STATION_FLAG
	        ,
	        NVL(SUBSTR(M05_SERVICE_FLAG, 12, 1), '0') INFO_CENTER_FLG
	        ,M05_KAITENBI
	        ,substr(A.M05_LOCATION.SDO_POINT.X,1,8) as M05_X
	        ,substr(A.M05_LOCATION.SDO_POINT.Y,1,8) as M05_Y
	    FROM
	        M05TENPO_INFO A
	        ,M05TENPO_SERVICE B
	        ,M03EKI C
	        ,M02ENSEN D
	        ,M93CALLNOTE E
	        ,M05TENPO_STAFF_COMMENT CMT
	    WHERE
	        A.M05_TENPO_CD = B.M05_TENPO_CD(+)
	        AND A.M05_TENPO_CD = E.M93_TENPO_CD(+)
	        AND A.M05_TENPO_CD = CMT.M05_TENPO_CD(+)
	        AND A.M05_TENPO_CD = '{$strShopCd}'
	        AND A.M05_KOUKAI_FLAG = 1
	        AND A.M05_EKI_CD01 = C.M03_EKI_CD(+)
	        AND C.M03_ENSEN_CD = D.M02_ENSEN_CD(+)

DOC_END;

        return $sql;
    }

	/**
	 * 店舗スタッフコメント取得
	 *
	 * @param ショップNo
	 * @return 店舗スタッフコメント情報
	 */
	public function getStaffComment($shopNo)
	{
		$db_params = array();
		$db_params['ShopCd'] = $shopNo;
		
		$sql  = "";
		$sql .= "SELECT ";
		$sql .= "  M05_TENPO_CD ";
		$sql .= ", M05_TENPO_COMMENT_ONLINE ";
		for ($i=1; $i<=Apm_Config_Shop::STAFF_COMMENT_NUM; $i++) {
			$num = sprintf("%02d", $i);
			$sql .= ", M05_STAFF_GAZOU_ONLINE".$num;
			$sql .= ", M05_STAFF_NAME_ONLINE".$num;
			$sql .= ", M05_STAFF_COMMENT_ONLINE".$num;
		}
		$sql .= "  FROM ";
		$sql .= "    M05TENPO_STAFF_COMMENT ";
		$sql .= " WHERE ";
		$sql .= "    M05_TENPO_CD = :ShopCd ";
		
		return $this->dbGetData($sql, $db_params);
	}
	/**
	 * 店舗スタッフコメントコンバート
	 *
	 * @param 店舗スタッフコメント情報
	 * @return 
	 */
	public function convertStaffComment($staffCommentData)
	{
		$staffComment = array();
		
		// 店舗コメントを表示用コンバート
		$staffComment['COMMENT'] = $this->convertHtmlTag($staffCommentData['M05_TENPO_COMMENT_ONLINE']);
		
		// 店舗スタッフを表示用コンバート
		$staffComment['STAFF'] = array();
		for ($i=1; $i<=Apm_Config_Shop::STAFF_COMMENT_NUM; $i++) {
			$num = sprintf("%02d", $i);
			// 写真
			$gazou   = $staffCommentData['M05_STAFF_GAZOU_ONLINE'.$num];
			// 名前
			$name    = $this->convertHtmlTag($staffCommentData['M05_STAFF_NAME_ONLINE'.$num]);
			// コメント
			$comment = $this->convertHtmlTag($staffCommentData['M05_STAFF_COMMENT_ONLINE'.$num]);
			// データが無ければ無視
			if (empty($gazou) && empty($name) && empty($comment)) {
				continue;
			}
			// コメントを表示用に
			
			// データセット
			$staffComment['STAFF'][] = array(
				'GAZOU'   => $gazou,
				'NAME'    => $name,
				'COMMENT' => $comment
			);
		}
		
		return $staffComment;
	}
	public function convertHtmlTag($strHtml)
	{
		$resHtml = $strHtml;
		// 特殊文字変換
		$resHtml = Apm_Util::replaceHtmlEntity($resHtml);
		// 機種依存文字変換
		$resHtml = Apm_Util::replaceUnicode($resHtml);
		// 改行CDを<br />へ変換
		$resHtml = mb_ereg_replace("\r", "", mb_ereg_replace("\n", "<br />", $resHtml));
		
		return $resHtml;
	}

	/**
	 * キャンペーン実施物件保持判定
	 *
	 * @param ショップNo
	 * @return 店舗コード（取得できなかった場合はnull）
	 */
	public function getCampaignBukken($shopNo)
	{
		$result = FALSE;
		$db_params = array();
		$db_params['today'] = date("Ymd");

$sql = <<< DOC_END

		SELECT
		        COUNT(*) CNT
		    FROM
		        ASNFC_USER.M94CAMPAIGN
		    WHERE
		        M94_DELETE_FLAG = 0
		        AND M94_MOBILE_KBN = 0
		        AND :today BETWEEN NVL(M94_START_YMD, '99999999') AND NVL(M94_END_YMD, '99999999')
		        AND M94_CAMPAIGN_CD IN (
		            34
		        )

DOC_END;

		$shopDtl = $this->dbGetData($sql, $db_params);

        // 物件が存在する場合
        if ($shopDtl["CNT"] > 0) $result = TRUE;

		return $result;
	}
	public function getCampaignExile($shopNo)
	{
		$result = FALSE;
		$db_params = array();
		$db_params['today'] = date("Ymd");

$sql = <<< DOC_END

		SELECT
		        COUNT(*) CNT
		    FROM
		        ASNFC_USER.M94CAMPAIGN
		    WHERE
		        M94_DELETE_FLAG = 0
		        AND M94_MOBILE_KBN = 0
		        AND :today BETWEEN NVL(M94_START_YMD, '99999999') AND NVL(M94_END_YMD, '99999999')
		        AND M94_CAMPAIGN_CD IN (
		            51
		        )

DOC_END;

		$shopDtl = $this->dbGetData($sql, $db_params);

        // 物件が存在する場合
        if ($shopDtl["CNT"] > 0) $result = TRUE;

		return $result;
	}
	
	/**
	 * ショップNoからCallクレヨンの0037番号をAPIより、取得して返す。
	 *
	 * @param	$shopCode	店舗コード
	 * @param	$ext		枝番
	 * @return	Callクレヨンの0037番号（取得できなかった場合はnull）
	 */
	public function getCallCrayonNumber($api, $serviceId, $shopCode, $ext) {
//		if (!$this->_config['callcrayons']['api']) return null;
		
//		$api = 'http://develop.specialist.jp/check.jsp';
		$cli = new Zend_Http_Client($api,
					array(
					      'maxredirects' => 1,
					      'timeout' => 10
					      )
					);
		$cli->setAdapter(new Zend_Http_Client_Adapter_Curl());
//		$cli->getAdapter()->setOptions(array(
//			'sslcapath'=> '/etc/ssl/certs'
//		));
		
		$params = array();
		$params['serviceId'] = $serviceId;
		$params['branchCd'] = $shopCode . 'x' . $ext;
		$cli->setParameterPost($params);

		try {
			$response = $cli->request(Zend_Http_Client::POST);
			
			$result = json_decode($response->getBody(), true);
			
			if ($result['result']['code'] == '0') {
				return $result['telno'];
			} else {
				return null;
			}
		} catch(Zend_Http_Client_Exception $e) {
			error_log('api result=' . $e->getMessage());
			return null;
		}
	}
}
?>

